package fun.sanguo.service.interact.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import fun.sanguo.mapper.interact.InteractPersonageDislikeMapper;
import fun.sanguo.model.dto.DataInfo;
import fun.sanguo.model.dto.PageInsert;
import fun.sanguo.model.dto.PageUpdate;
import fun.sanguo.model.dto.interact.InteractPersonageDislikeInsert;
import fun.sanguo.model.dto.interact.InteractPersonageDislikeResult;
import fun.sanguo.model.dto.interact.InteractPersonageDislikeUpdate;
import fun.sanguo.model.entity.interact.InteractPersonageDislikeEntity;
import fun.sanguo.model.enums.ResEnums;
import fun.sanguo.service.interact.InteractPersonageDislikeService;
import fun.sanguo.utils.DateUtils;
import fun.sanguo.utils.IdUtils;
import fun.sanguo.utils.exception.ArtificialException;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 互动-人物厌恶记录 Service实现类
 *
 * @author ZYP
 * @date 2023-10-13
 */
@Service
public class InteractPersonageDislikeServiceImpl implements InteractPersonageDislikeService {

    @Resource
    private InteractPersonageDislikeMapper interactPersonageDislikeMapper;

    /**
     * 新增
     *
     * @param pageInsert
     * @param userId
     * @param userIp
     * @return
     * @throws ArtificialException
     */
    @Override
    public DataInfo<InteractPersonageDislikeResult> insert(PageInsert<InteractPersonageDislikeInsert> pageInsert, String userId, String userIp) throws ArtificialException {
        // 新增参数
        InteractPersonageDislikeEntity interactPersonageDislikeEntity = new InteractPersonageDislikeEntity();
        // 转换新增参数
        try {
            // 接收参数
            InteractPersonageDislikeInsert interactPersonageDislikeInsert = new ObjectMapper().convertValue(pageInsert.getParam(), InteractPersonageDislikeInsert.class);
            // 赋值到实体类
            BeanUtils.copyProperties(interactPersonageDislikeInsert, interactPersonageDislikeEntity);
            interactPersonageDislikeEntity.setUserId(userId);
            interactPersonageDislikeEntity.setUserIp(userIp);
            interactPersonageDislikeEntity.setDislikeTime(new Date());
            // 其他参数赋值
            interactPersonageDislikeEntity.setId(String.valueOf(new IdUtils().nextId()));
            interactPersonageDislikeEntity.setCreateBy("system");
            interactPersonageDislikeEntity.setCreateTime(DateUtils.getTime(DateUtils.DATE_FORMAT_11));
            interactPersonageDislikeEntity.setUpdateBy("system");
            interactPersonageDislikeEntity.setUpdateTime(DateUtils.getTime(DateUtils.DATE_FORMAT_11));
            interactPersonageDislikeEntity.setVersion(1);
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_PARAM.getCode(), ResEnums.ERR_PARAM.getMsg(), e);
        }
        // 新增数据并得到操作结果
        try {
            // 新增
            int amount = interactPersonageDislikeMapper.insert(interactPersonageDislikeEntity);
            // 查询指定人物的厌恶数量、指定用户是否厌恶
            InteractPersonageDislikeResult result = getSummaryByUserPersonage(userId, interactPersonageDislikeEntity.getPersonageId());
            // 增加操作结果
            result.setResult(amount > 0);
            // 返回操作结果
            return new DataInfo<>(result);
        } catch (ArtificialException ae) {
            throw ae;
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_MYSQL.getCode(), ResEnums.ERR_MYSQL.getMsg(), e);
        }
    }

    /**
     * 删除
     *
     * @param pageUpdate
     * @param userId
     * @return
     * @throws ArtificialException
     */
    @Override
    public DataInfo<InteractPersonageDislikeResult> delete(PageUpdate<InteractPersonageDislikeUpdate> pageUpdate, String userId) throws ArtificialException {
        // 删除参数
        InteractPersonageDislikeEntity interactPersonageDislikeEntity = new InteractPersonageDislikeEntity();
        // 转换删除参数
        try {
            // 接收参数
            InteractPersonageDislikeUpdate interactPersonageDislikeUpdate = new ObjectMapper().convertValue(pageUpdate.getParam(), InteractPersonageDislikeUpdate.class);
            // 赋值到实体类
            interactPersonageDislikeEntity.setId(interactPersonageDislikeUpdate.getId());
            // 其他参数赋值
            interactPersonageDislikeEntity.setUpdateBy("system");
            interactPersonageDislikeEntity.setUpdateTime(DateUtils.getTime(DateUtils.DATE_FORMAT_11));
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_PARAM.getCode(), ResEnums.ERR_PARAM.getMsg(), e);
        }
        // 删除数据并得到操作结果
        try {
            // 查询记录信息
            InteractPersonageDislikeEntity record = interactPersonageDislikeMapper.getById(interactPersonageDislikeEntity.getId());
            // 非当前登陆用户则报错
            if (record == null || StringUtils.isEmpty(record.getUserId()) || !record.getUserId().equals(userId)) {
                throw new ArtificialException(ResEnums.ERR_USER_NOTAllOW.getCode(), ResEnums.ERR_USER_NOTAllOW.getMsg(), null);
            }
            // 删除
            int amount = interactPersonageDislikeMapper.delete(interactPersonageDislikeEntity);
            // 查询指定人物的厌恶数量、指定用户是否厌恶
            InteractPersonageDislikeResult result = getSummaryByUserPersonage(userId, record.getPersonageId());
            // 增加操作结果
            result.setResult(amount > 0);
            // 返回操作结果
            return new DataInfo<>(result);
        } catch (ArtificialException ae) {
            throw ae;
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_MYSQL.getCode(), ResEnums.ERR_MYSQL.getMsg(), e);
        }
    }

    /**
     * 查询指定人物的厌恶数量及是否被指定用户厌恶
     *
     * @param userId
     * @param personageId
     * @return
     * @throws ArtificialException
     */
    @Override
    public InteractPersonageDislikeResult getSummaryByUserPersonage(String userId, String personageId) throws ArtificialException {
        try {
            // 根据用户与人物查询记录
            InteractPersonageDislikeEntity interactPersonageDislikeEntity = interactPersonageDislikeMapper.getByUserPersonage(userId, personageId);
            // 查询指定人物的厌恶数量
            int amount = interactPersonageDislikeMapper.getSummaryByPersonage(personageId);
            // 封装返回结果
            InteractPersonageDislikeResult interactPersonageDislikeResult = new InteractPersonageDislikeResult();
            if (interactPersonageDislikeEntity != null) {
                interactPersonageDislikeResult.setInteractId(interactPersonageDislikeEntity.getId());
            }
            interactPersonageDislikeResult.setAmount(amount);
            // 返回查询结果
            return interactPersonageDislikeResult;
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_MYSQL.getCode(), ResEnums.ERR_MYSQL.getMsg(), e);
        }
    }

    /**
     * 查询所有人物的厌恶数量及是否被指定用户厌恶
     *
     * @param userId
     * @return
     * @throws ArtificialException
     */
    @Override
    public Map<String, InteractPersonageDislikeResult> getSummaryByUser(String userId) throws ArtificialException {
        try {
            // 根据用户查询记录
            List<InteractPersonageDislikeEntity> interactPersonageDislikeEntityList = interactPersonageDislikeMapper.getByUser(userId);
            // 查询所有人物的厌恶数量
            List<JSONObject> summaryList = interactPersonageDislikeMapper.getSummary();
            // 返回结果
            Map<String, InteractPersonageDislikeResult> interactPersonageDislikeResultMap = new HashMap<>();
            // 先遍历统计结果，封装所有人物
            summaryList.forEach(summary -> {
                InteractPersonageDislikeResult interactPersonageDislikeResult = new InteractPersonageDislikeResult();
                interactPersonageDislikeResult.setAmount(summary.getLong("AMOUNT"));
                interactPersonageDislikeResultMap.put(summary.getString("PERSONAGE_ID"), interactPersonageDislikeResult);
            });
            // 遍历用户厌恶列表
            interactPersonageDislikeEntityList.forEach(interactPersonageDislikeEntity -> {
                interactPersonageDislikeResultMap.get(interactPersonageDislikeEntity.getPersonageId()).setInteractId(interactPersonageDislikeEntity.getId());
            });
            // 返回查询结果
            return interactPersonageDislikeResultMap;
        } catch (Exception e) {
            throw new ArtificialException(ResEnums.ERR_MYSQL.getCode(), ResEnums.ERR_MYSQL.getMsg(), e);
        }
    }
}
